//
//  YHCycleImage.m
//  CollectionView轮播图
//
//  Created by dllo on 16/8/4.
//  Copyright © 2016年 yh. All rights reserved.
//

#import "YHCycleImage.h"
#import "SecCollectionViewCell.h"

@interface YHCycleImage () <UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;

@end


@implementation YHCycleImage

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self createCollectionView];
        _picArray = [NSMutableArray array];
    }
    return self;
}

- (void)createPicArray:(NSMutableArray *)array {
    UIImage *image1 = [array firstObject];
    UIImage *image2 = [array lastObject];
    for (NSInteger i = 0; i < array.count; i++) {
        [self.picArray addObject:array[i]];
    }
    [self.picArray addObject:image1];
    [self.picArray insertObject:image2 atIndex:0];
}

- (void)createCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(self.bounds.size.width, 270);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 270) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.pagingEnabled = YES;
    [self addSubview:self.collectionView];
    [self.collectionView registerNib:[UINib nibWithNibName:@"SecCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"REUSE"];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.picArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SecCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"REUSE" forIndexPath:indexPath];
    cell.picImageView.image = self.picArray[indexPath.row];
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.collectionView.contentOffset.x == self.bounds.size.width * (self.picArray.count - 1)) {
        self.collectionView.contentOffset = CGPointMake(self.frame.size.width, 0);
    }
    if (self.collectionView.contentOffset.x == 0) {
        self.collectionView.contentOffset = CGPointMake(self.frame.size.width * (self.picArray.count - 2), 0);
    }
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
